<template>
  <div class="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <div class="text-center">
          <!-- 加载状态 -->
          <div v-if="isLoading" class="space-y-4">
            <div class="flex justify-center">
              <svg class="animate-spin h-12 w-12 text-primary-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </div>
            <h2 class="text-lg font-medium text-gray-900">
              Processing Google Authentication...
            </h2>
            <p class="text-sm text-gray-500">
              Please wait while we complete your sign-in.
            </p>
          </div>

          <!-- 成功状态 -->
          <div v-else-if="isSuccess" class="space-y-4">
            <div class="flex justify-center">
              <svg class="h-12 w-12 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 class="text-lg font-medium text-gray-900">
              Authentication Successful!
            </h2>
            <p class="text-sm text-gray-500">
              Redirecting to dashboard...
            </p>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="error" class="space-y-4">
            <div class="flex justify-center">
              <svg class="h-12 w-12 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h2 class="text-lg font-medium text-gray-900">
              Authentication Failed
            </h2>
            <p class="text-sm text-red-600">
              {{ error }}
            </p>
            <div class="mt-6">
              <router-link
                to="/login"
                class="btn-primary"
              >
                Back to Login
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { GoogleAuthUtils } from '../utils/googleAuth'
import { trpc } from '../utils/trpc'

// 路由和store
const router = useRouter()
const authStore = useAuthStore()
const toast = useToast()

// 组件状态
const isLoading = ref(true)
const isSuccess = ref(false)
const error = ref('')

// 处理Google OAuth回调
async function handleGoogleCallback() {
  try {
    // 从URL中提取授权码或错误
    const code = GoogleAuthUtils.extractCodeFromUrl()
    const urlError = GoogleAuthUtils.extractErrorFromUrl()

    if (urlError) {
      throw new Error(`Google OAuth error: ${urlError}`)
    }

    if (!code) {
      throw new Error('No authorization code received from Google')
    }

    // 使用授权码进行认证
    const redirectUri = `${window.location.origin}/auth/google/callback`
    const result = await trpc.auth.googleAuthCallback.mutate({
      code,
      redirectUri
    })

    if (result.success && result.data) {
      // 保存认证信息
      authStore.user = result.data.user
      authStore.token = result.data.token
      
      localStorage.setItem('auth_token', result.data.token)
      localStorage.setItem('auth_user', JSON.stringify(result.data.user))

      isSuccess.value = true
      toast.success(result.message || 'Google authentication successful')

      // 延迟重定向以显示成功状态
      setTimeout(() => {
        router.push('/dashboard')
      }, 2000)
    } else {
      throw new Error(result.message || 'Authentication failed')
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Authentication failed'
    toast.error(error.value)
  } finally {
    isLoading.value = false
    
    // 清理URL参数
    GoogleAuthUtils.cleanupUrl()
  }
}

// 组件挂载时处理回调
onMounted(() => {
  // 检查是否已经登录
  if (authStore.isAuthenticated) {
    router.push('/dashboard')
    return
  }

  // 处理Google OAuth回调
  handleGoogleCallback()
})
</script>
